package agriculture.config;

import agriculture.bean.Payment;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;


@ConfigurationProperties(prefix = "alipay")
@Component
@Data
public class AlipayTemplate {
    private String appId;
    private String merchantPrivateKey;
    private String alipayPublicKey;
    private String notifyUrl;
    private String returnUrl;
    private String signType;
    private String charset;
    private String gatewayUrl;
    private String timeout = "2m"; // 默认2分钟内必须支付

    public String pay(Payment payment) throws AlipayApiException {
        // 创建支付宝客户端
        AlipayClient alipayClient = new DefaultAlipayClient(
                gatewayUrl,
                appId,
                merchantPrivateKey,
                "json",
                charset,
                alipayPublicKey,
                signType
        );

        // 创建支付请求
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl(returnUrl);
        request.setNotifyUrl(notifyUrl);

        // 构造参数
        request.setBizContent("{\"out_trade_no\":\"" + payment.getOrderNumber() + "\","
                + "\"total_amount\":\"" + payment.getPayAmount() + "\","
                + "\"subject\":\"支付订单：" + payment.getOrderNumber()+ "\","
                + "\"body\":\"支付方式：" + payment.getPayType() + "\","
                + "\"timeout_express\":\"" + timeout + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");



        // 执行请求，返回HTML表单页面
        return alipayClient.pageExecute(request).getBody();
    }
}
